from backend.api.connection import POOL
# from connection import POOL   # 单独运行用这个
import datetime

# 同步计划
# 返回
# {
#  'ok': 1,
#  'msg':''}
def syncLearning(pid, word, ignore):
    conn = POOL.connection()
    cur = conn.cursor()
    response = {'ok': 0, 'msg': ''}
    word = repr(word)
    # 不认识的处理
    if int(ignore) == 1:
        sql = "UPDATE plan_{} SET `ignore` = 1 WHERE word = {}".format(pid, word)
        cur.execute(sql)
        conn.commit()
        response['msg'] = 'ignore'
        response['ok'] = 1
        return response
    else:
        learn_time = datetime.datetime.now().strftime("%Y-%m-%d")

        # 更新计划管理表中的待学数量，每日待学数量
        sql = "UPDATE planlist SET remain_num = remain_num-1,day_remain_num = day_remain_num-1 " \
              "WHERE pid = {}".format(pid)
        cur.execute(sql)
        conn.commit()

        # 更新学习计划表中的标记
        sql = "UPDATE plan_{} SET learn_times = learn_times + 1,last_time = {}, `ignore` = 0 " \
              "WHERE word = {}".format(pid, "{1}{0}{1}".format(learn_time, "'"), word)
        cur.execute(sql)
        conn.commit()

        # 打卡检测
        sql = "SELECT day_remain_num,create_time,check_in_info FROM planlist WHERE pid = {}".format(pid)
        cur.execute(sql)
        result = cur.fetchone()
        if int(result[0]) <= 0:
            date = datetime.datetime.strptime(result[1].strftime("%Y-%m-%d"), "%Y-%m-%d")
            days = (datetime.datetime.now() - date).days
            if result[2] is None:
                check_in_info = str(days) + ','
            else:
                check_in_info = str(result[2]) + str(days) + ','
            sql = "UPDATE planlist SET check_in_info = {} " \
                  "WHERE pid = {}".format("{1}{0}{1}".format(check_in_info, "'"), pid)
            print(sql)
            cur.execute(sql)
            conn.commit()

        response['ok'] = 1
        response['msg'] = 'learn'
        return response


if __name__ == '__main__':
    syncLearning(1, "abbreviation", 0)